package com.qfhd.soft.cjzcore.TaskCenter.CSJ;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.qfhd.soft.cjzcore.Core.CJLogger;
import com.qfhd.soft.cjzcore.Listener.CJAdListener;
import com.qfhd.soft.cjzcore.TaskCenter.CJAdCenter;
import com.qfhd.soft.cjzcore.TaskCenter.TTAdManagerHolder;

import java.util.List;

public class CJCSJ_Navi {

    private Context mContext;
    private TTNativeExpressAd mTTAd = null;//信息流广告
    private TTAdNative mTTAdNative  = null;

    private static CJCSJ_Navi CJCSJNavi;
    public static CJCSJ_Navi getInstance(){
        if(CJCSJNavi == null){
            synchronized (CJCSJ_Navi.class){
                CJCSJNavi = new CJCSJ_Navi();
            }
        }
        return CJCSJNavi;
    }

    public void releaseAd(){
        CJLogger.v("releaseAd");
        if(mTTAd != null){
            mTTAd = null;
        }
        if(mTTAdNative != null){
            mTTAdNative = null;
        }
    }

    public void getNativeAd(Context context, int width, int height, FrameLayout mExpressContainer, Activity activity, CJAdListener statusListener){

        releaseAd();

        //设置广告参数
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(CJCSJsdk.Message) //广告位id
                .setSupportDeepLink(true)
//                .setNativeAdType(TTAdConstant.INTERACTION_TYPE_DOWNLOAD) //2在浏览器内打开 （普通类型）3落地页（普通类型），4:应用下载，5:拨打电话 -1 未知类型
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(width,height) //期望个性化模板广告view的size,单位dp
                .setImageAcceptedSize(640,320) //这个参数设置即可，不影响个性化模板广告的size
                .build();
        //加载广告
        mTTAdNative  = TTAdManagerHolder.get().createAdNative(context);
        TTAdManagerHolder.get().requestPermissionIfNecessary(context);
        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
//                TToast.show(NativeExpressActivity.this, "load error : " + code + ", " + message);
                CJLogger.v(" getNativeAd onError:"+message);
                mExpressContainer.removeAllViews();
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0){
                    return;
                }
                mTTAd = ads.get(0);
                bindAdListener(mTTAd,mExpressContainer,activity,statusListener);
                mTTAd.render();//调用render开始渲染广告
            }
        });
    }

    private void bindAdListener(TTNativeExpressAd ad, FrameLayout mExpressContainer, Activity activity, CJAdListener statusListener){
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
//                TToast.show(mContext, "广告被点击");
                CJLogger.v("onAdClicked");
                if(statusListener != null){
                    statusListener.onStatus(CJAdCenter.AD_Status_Click);
                }
            }

            @Override
            public void onAdShow(View view, int type) {
//                TToast.show(mContext, "广告展示");
                CJLogger.v("Native Ad show");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
//                Log.e("ExpressView","render fail:"+(System.currentTimeMillis() - startTime));
//                TToast.show(mContext, msg+" code:"+code);
                CJLogger.v("onRenderFail");
                if(statusListener != null){
                    statusListener.onStatus(CJAdCenter.AD_Status_Close);
                }
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //返回view的宽高 单位 dp
//                TToast.show(mContext, "渲染成功");
                //在渲染成功回调时展示广告，提升体验
                CJLogger.v("onRenderSuccess");
                if(statusListener != null){
                    statusListener.onStatus(CJAdCenter.AD_Status_OpenFrame);
                }
                mExpressContainer.removeAllViews();
                mExpressContainer.addView(view);
            }
        });

        bindDislike(ad,false,activity,mExpressContainer);
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD){
            return;
        }
        //可选，下载监听设置
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
//                TToast.show(NativeExpressActivity.this, "点击开始下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!mHasShowDownloadActive) {
//                    mHasShowDownloadActive = true;
//                    TToast.show(NativeExpressActivity.this, "下载中，点击暂停", Toast.LENGTH_LONG);
//                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "下载暂停，点击继续", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "下载失败，点击重新下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onInstalled(String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "安装完成，点击图片打开", Toast.LENGTH_LONG);
                if(statusListener != null){
                    statusListener.onStatus(CJAdCenter.AD_Status_Install);
                }
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "点击安装", Toast.LENGTH_LONG);
                if(statusListener != null){
                    statusListener.onStatus(CJAdCenter.AD_Status_Download);
                }
            }
        });
    }

    /**
     * 设置广告的不喜欢，注意：强烈建议设置该逻辑，如果不设置dislike处理逻辑，则模板广告中的 dislike区域不响应dislike事件。
     * @param ad
     * @param customStyle 是否自定义样式，true:样式自定义
     */
    private void bindDislike(TTNativeExpressAd ad, boolean customStyle, Activity activity, FrameLayout mExpressContainer) {
        //使用默认模板中默认dislike弹出样式
        ad.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onSelected(int position, String value) {
//                TToast.show(mContext, "点击 " + value);
                //用户选择不喜欢原因后，移除广告展示
                mExpressContainer.removeAllViews();
            }

            @Override
            public void onCancel() {
//                TToast.show(mContext, "点击取消 ");
            }
        });
    }
}
